<template>
  <div class="component-icon-btn" @click="handleUnderline">
    <div class="component-icon-btn-icon">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
        <path d="M5 2v6a3 3 0 106 0V2h1v6a4 4 0 11-8 0V2h1zM4 13h8v1H4z" fill="#3D4757" />
      </svg>
    </div>
  </div>
</template>

<script>
import {
  undoManager
} from '../Utils.js'

export default {
  props: {
    context: {
      type: Object,
      required: true
    }
  },
  data: function() {
    return {

    }
  },
  mounted: function() {

  },
  methods: {
    handleUnderline() {
      const table = this.context.hot
      const selected = table.getSelected()
      if (!selected) {
        this.$message('请选择单元格')
        return
      }

      let startRow = selected[0]
      let startCol = selected[1]
      let endRow = selected[2]
      let endCol = selected[3]
      let tmp = endRow
      if (startRow > endRow) {
        endRow = startRow
        startRow = tmp
      }
      tmp = endCol
      if (startCol > endCol) {
        endCol = startCol
        startCol = tmp
      }
      const _this = this
      let oldUnderlineStyle = updateCellsUnderlineStyle(this.context, startRow, startCol, endRow, endCol)
      undoManager.add({
        redo: function() {
          oldUnderlineStyle = updateCellsUnderlineStyle(_this.context, startRow, startCol, endRow, endCol)
        },
        undo: function() {
          oldUnderlineStyle = updateCellsUnderlineStyle(_this.context, startRow, startCol, endRow, endCol,
            oldUnderlineStyle)
        }
      })
    }
  }

}

function updateCellsUnderlineStyle(context, startRow, startCol, endRow, endCol, prevUnderLine) {
  const oldUnderlineStyle = {}
  const hot = context.hot
  for (let i = startRow; i <= endRow; i++) {
    for (let j = startCol; j <= endCol; j++) {
      const td = hot.getCell(i, j)
      const cellDef = context.getCell(i, j)
      if (!cellDef) {
        continue
      }
      let underline = 'underline'
      if (prevUnderLine) {
        underline = prevUnderLine[i + ',' + j]
      }
      const cellStyle = cellDef.cellStyle
      oldUnderlineStyle[i + ',' + j] = cellStyle.underline
      if (cellStyle.underline) {
        cellStyle.underline = false
      } else {
        cellStyle.underline = true
      }
    }
  }
  hot.render()
  return oldUnderlineStyle
}
</script>
